package com.Jian.reggie.controller;

import com.Jian.reggie.common.R;
import com.Jian.reggie.impl.Category;
import com.Jian.reggie.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * ClassName: CategoryController
 * Package: com.Jian.reggie.controller
 * Description:
 *
 * @Author 蹇泽阳
 * @Create 2023/11/27 14:31
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
  
  @Autowired
  private CategoryService categoryService;
  
  /**
   * 新增分类
   */
  @PostMapping
  public R addCategory(@RequestBody Category category) {
    categoryService.save(category);
    return R.success("新增成功");
  }
  
  /**
   * 分类信息查询
   */
  @GetMapping("/page")
  public R<Page> getCategoryPage(Integer page, Integer pageSize) {
    Page<Category> categoryPage = new Page<>(page, pageSize);
    LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
    // 根据sort字段排序
    wrapper.orderByAsc(Category::getSort);
    categoryService.page(categoryPage, wrapper);
    
    return R.success(categoryPage);
  }
  
  /**
   * 删除分类
   */
  @DeleteMapping
  public R deleteCategory(String ids) {
    categoryService.remove(ids);
    return R.success("删除成功");
  }
  
  /**
   * 修改分类
   */
  @PutMapping
  public R updateCategory(@RequestBody Category category) {
    categoryService.updateById(category);
    return R.success("修改成功");
  }
  
  /**
   * 根据type 查询分类列表
   */
  @GetMapping("/list")
  public R<List<Category>> getCategoryList(Category category) {
    LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(category.getType() != null, Category::getType, category.getType());
    wrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
    List<Category> categoryList = categoryService.list(wrapper);
    return R.success(categoryList);
  }
}
